import 'package:dio/dio.dart';
import 'package:hive/hive.dart';

class HttpUtil {
  static final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'https://sf.giftwl.com/api',
      connectTimeout: const Duration(milliseconds: 10000),
      receiveTimeout: const Duration(milliseconds: 3000),
    ),
  );

  static void initialize() {
    // 添加拦截器
    _dio.interceptors.add(AuthTool());
  }

  static get(String path, {Map<String, dynamic>? params}) async {
    try {
      Response response = await _dio.get(path, queryParameters: params);
      return response.data;
    } on DioException catch (e) {
      print('----get        $e');
    }
  }

  static post(String path, {Map<String, dynamic>? params}) async {
    try {
      Response response = await _dio.post(path, data: params);
      return response.data;
    } on DioException catch (e) {
      print('----post        $e');
    }
  }

  static postFile(String path, {Map<String, dynamic>? params}) async {
    try {
      FormData formData = FormData.fromMap(params!);
      Response response = await _dio.post(path, data: formData);
      return response.data;
    } on DioException catch (e) {
      print('----postFile        $e');
    }
  }
}

class AuthTool extends Interceptor {
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 获取盒子
    var box = Hive.box('myBox');
    // 获取存储的数据
    String? token = box.get('token');
    print("-----url    ${options.baseUrl}${options.path}");
    print("-----token    $token");
    options.headers["token"] = token;
    return super.onRequest(options, handler);
  }

  @override
  onResponse(Response response, ResponseInterceptorHandler handler) {
    // 请求成功打印返回数据    //在此处做请求拦截配置
    return super.onResponse(response, handler);
  }

  @override
  onError(DioException err, ErrorInterceptorHandler handler) {
    // 请求错误打印error
    print("----------Error----------- $err");
    return super.onError(err, handler);
  }
}
